<template>
  <div class="app-container">
    <el-row :gutter="12">
      <el-col :span="17">
        <el-form :model="queryCpAccountParams" ref="queryRef" v-show="showSearch">
          <el-row :gutter="12">
            <el-col :span="6">
              <el-form-item label="交易对手" prop="partyName">
                <el-input
                    v-model="queryCpAccountParams.partyName"
                    clearable
                    size="mini"
                    :style="{width: '100%'}"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1.5">
              <el-form-item>
                <el-button type="primary" icon="Search" size="mini" style="margin: 3px 3px"
                v-hasPermi="['account:cpaccount:list']"
                           @click="handlCounterpartyQuery">搜索
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="12" style="margin: 0px 1px">
          <el-button
              type="primary"
              style="margin: 3px 3px"
              icon="Plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['account:cpaccount:add']"
          >新增
          </el-button>
          <el-button
              type="success"
              style="margin: 3px 3px"
              icon="Edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['account:cpaccount:edit']"
          >修改
          </el-button>
          <el-button
              type="danger"
              style="margin: 3px 3px"
              icon="Delete"
              size="mini"
              :disabled="single"
              @click="handleDelete"
              v-hasPermi="['account:cpaccount:remove']"
          >删除
          </el-button>
          <el-button
              type="danger"
              style="margin: 3px 3px"
              icon="Plus"
              size="mini"
              :disabled="single3"
              @click="handleStop"
              v-hasPermi="['account:cpaccount:stop']"
          >停用
          </el-button>
          <el-button
              type="success"
              style="margin: 3px 3px"
              icon="Plus"
              size="mini"
              :disabled="single4"
              @click="handleStart"
              v-hasPermi="['account:cpaccount:start']"
          >启用
          </el-button>
        </el-row>
        <el-row>
          <div class="wrapper" ref="wrapper">
            <xTable class="wrapper" ref="refCountpartyTable" :height="tableHeight" v-loading="loading" :data="cpAccountList" multiple="false"
                    refId="refCountpartyTable" @selection-change="handleCounterpartySelectionChange">
              <template #columList>
                <el-table-column label="序号" type="index"/>
                <el-table-column label="交易对手名称" align="left" prop="partyName"/>
                <el-table-column label="客户类型" align="left" prop="partyName">
                  <template #default="scope">
                <span>
                  {{ scope.row.partyType == 1 ? "持牌金融机构" : (scope.row.partyType == 2 ? "资管机构" : "非持牌金融机构") }}
                </span>
                  </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="status" v-if="true">
                  <template #default="scope">
                <span>
                  {{
                    scope.row.status == -1 ? "审批中" : (scope.row.status == 0 ? "新建" : (scope.row.status == 1 ? "启用" : "停用"))
                  }}
                </span>
                </template>
              </el-table-column>
            </template>
          </xTable>
          </div>
          <pagination
              style="margin:10px 0 10px 0;float:right"
              v-show="cpAccountTotal>0"
              :total="cpAccountTotal"
              v-model:page="queryCpAccountParams.pageNum"
              v-model:limit="queryCpAccountParams.pageSize"
              @pagination="getCounterpartyLists"
          />
        </el-row>

      </el-col>
      <el-divider direction="vertical" content-position="center"></el-divider>
      <el-col :span="6">
        <div class="page-title">
          <el-space>
            对手信息
          </el-space>
        </div>
        <el-form ref="countPartyFromRef" :model="countPartyForm" :rules="countPartyRules" label-width="110px">
          <el-form-item align="right" label="对手名称" prop="partyName">
            <el-input v-model="countPartyForm.partyName" :disabled="disableFlag" :style="{width:'100%'}" maxlength="50"/>
          </el-form-item>
          <el-form-item align="right" label="客户类型" prop="partyType">
            <el-select v-model="countPartyForm.partyType" placeholder="请选择" :style="{width:'100%'}"
                       :disabled="disableFlag">
              <el-option label="持牌金融机构" value=1></el-option>
              <el-option label="资管机构" value=2></el-option>
              <el-option label="非持牌金融机构" value=3></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div style="text-align: center;margin: 5px 5px">
          <template v-if="buttonOpen != 0">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="CountPartyInfo">
import {computed, onMounted, ref, watch} from "vue";
import xTable from "@/xquant/base/xTable";
import {
  getCpAccountList,
  deleteCounterparty,
  saveCounterparty,
  updateCounterparty,
} from '@/api/account/cpaccountmanagement'
const tableHeight = ref(null);
const {proxy} = getCurrentInstance();
const {M_TYPE, A_TYPE, CURRENCY, productType} = proxy.useDict("M_TYPE", "A_TYPE", "CURRENCY", "productType");
onMounted(()=>{
     tableHeight.value = proxy.$refs.wrapper.parentElement.parentNode.clientHeight * 0.85
  window.onresize = () => {
    return (() => {
      tableHeight.value = proxy.$refs.wrapper.parentElement.parentNode.clientHeight * 0.80
    })();
  }
})

// 用户组列表
const cpAccountList = ref([]);
// 用户组列表
const templateSelection = ref({});
const buttonOpen = ref(0); //0表示关闭，1表示打开

const loading = ref(true);
const showSearch = ref(true);
const disableFlag = ref(true);
//
const ids = ref([]);
//
const names = ref([]);
//索引
const indexs = ref([]);
//数据
const rows = ref([]);

const single = ref(true);
const single4 = ref(true);
const single3 = ref(true);
const multiple = ref(true);
const cpAccountTotal = ref(0);
const selectionAccountRow = ref([]);
const action = ref('');

const data = reactive({
  countPartyRules: {
    partyName: [{required: true, message: "交易对手不能为空", trigger: "blur"}],
    partyType: [{required: true, message: "客户类型不能为空", trigger: "blur"}],
  },
  countPartyForm: {
    partyId: null,
    partyName: null,
    status: null,
    partyType: null,
  },
  queryCpAccountParams: {
    pageNum: 1,
    pageSize: 20,
    partyName: undefined,
  },
});
const {
  countPartyForm,
  queryCpAccountParams,
  countPartyRules,
} = toRefs(data);


/** 查询按钮 */
function handlCounterpartyQuery() {
  getCounterpartyLists();
}

/** 查询对手账户列表 */
function getCounterpartyLists() {
  loading.value = false;
  getCpAccountList(queryCpAccountParams.value).then(response => {
    cpAccountList.value = response.list;
    cpAccountTotal.value = response.total;
    loading.value = false;
  });
}

/**对手 新增按钮操作 */
function handleAdd() {
  reset();
  disableFlag.value = false;
  countPartyForm.value.status = 0;
  buttonOpen.value = 1;
  action.value = 'add';
}

/** 对手  修改按钮操作 */
function handleUpdate() {
  buttonOpen.value = 1;
  action.value = 'update';
  disableFlag.value = false;
}

/** 删除按钮操作 */
function handleDelete() {
  const partyNames = names.value;
  const counterparty = rows.value[0];
  proxy.$modal.confirm('是否确认删除对手名称为 "' + partyNames + '"的数据项？').then(function () {
    return deleteCounterparty(counterparty);
  }).then(() => {
    getCounterpartyLists();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/**
 *
 * 修改/新增   保存操作
 * */
function submitForm() {
  proxy.$refs["countPartyFromRef"].validate(valid => {
    if (valid) {
      if (action.value == 'update') {
        updateCounterparty(countPartyForm.value).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess("修改成功");
            queryCpAccountParams.value.partyName = null;
            getCounterpartyLists();
            reset();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      } else {
        saveCounterparty(countPartyForm.value).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess("新增成功");
            reset();
            getCounterpartyLists();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      }
    }
  });
}

/**
 *
 * 多选框  选中数据
 * */
function handleCounterpartySelectionChange(selection) {
  if (selection.length == 0) {
    ids.value = [];
    indexs.value = [];
    names.value = [];
  } else {
    ids.value = selection.map(item => item.partyId);
    indexs.value = selection.map(item => item.index);
    rows.value = selection.map(item => item);
    names.value = selection.map(item => item.partyName)
  }
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  if (selection.length == 1) {
    buttonOpen.value = 0;
    disableFlag.value = true;
    reset();
    countPartyForm.value.partyName = rows.value[0].partyName;
    countPartyForm.value.partyType = rows.value[0].partyType;
    countPartyForm.value.status = rows.value[0].status;
    countPartyForm.value.partyId = rows.value[0].partyId;
    if (rows.value[0].status == 0 || rows.value[0].status == 2) {
      single4.value = false;
    }
    if (rows.value[0].status == 1) {
      single3.value = false;
    }
  }
  if (selection.length != 1) {
    buttonOpen.value = 0;
    disableFlag.value = true;
    countPartyForm.value = [];
    single3.value = true;
    single4.value = true;
  }
}

/** 取消添加按钮 */
function cancel() {
  buttonOpen.value = 0;
  disableFlag.value = true;
}

/** 表单重置 */
function reset() {
  countPartyForm.value = {
    partyId: null,
    partyName: null,
    partyType: null,
    status: null
  };
  proxy.resetForm("countPartyFromRef");
}

function rowClick(row, column, event) {
  let refsElTable = proxy.$refs.refCountpartyTable; // 获取表格对象
  let findRow = selectionAccountRow.value.find(c => c.rowIndex == row.rowIndex);
  if (findRow) {
    refsElTable.toggleRowSelection(row, false);
    return;
  }
  refsElTable.clearSelection();
  refsElTable.toggleRowSelection(row); // 调用选中行方法
};

function rowStyle({row, rowIndex}) {
  Object.defineProperty(row, 'rowIndex', { //给每一行添加不可枚举属性rowIndex来标识当前行
    value: rowIndex,
    writable: true,
    enumerable: false
  })
};

// 停用
function handleStop() {
  countPartyForm.value.partyId = rows.value[0].partyId;
  countPartyForm.value.partyName = rows.value[0].partyName;
  countPartyForm.value.status = 2;
  updateCounterparty(countPartyForm.value).then(response => {
    if (response.success) {
      proxy.$modal.msgSuccess("修改成功");
      queryCpAccountParams.value.partyName = null;
      reset();
      getCounterpartyLists();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
}

// 启用
function handleStart() {
  countPartyForm.value.partyId = rows.value[0].partyId;
  countPartyForm.value.partyName = rows.value[0].partyName;
  countPartyForm.value.status = 1;
  updateCounterparty(countPartyForm.value).then(response => {
    if (response.success) {
      proxy.$modal.msgSuccess("修改成功");
      queryCpAccountParams.value.partyName = null;
      reset();
      getCounterpartyLists();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
}

getCounterpartyLists();
</script>

<style lang="scss" scoped>
.wrapper{
  width: calc(100% );
}
.el-table{
  padding-top: 0px !important;
}
</style>
